package com.kong.meirimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.kong.common.constant.ProductConstant;
import com.kong.meirimall.product.dao.AttrAttrgroupRelationDao;
import com.kong.meirimall.product.dao.AttrGroupDao;
import com.kong.meirimall.product.dao.CategoryDao;
import com.kong.meirimall.product.entity.AttrAttrgroupRelationEntity;
import com.kong.meirimall.product.entity.AttrGroupEntity;
import com.kong.meirimall.product.entity.CategoryEntity;
import com.kong.meirimall.product.service.CategoryService;
import com.kong.meirimall.product.vo.AttrGroupRelationVo;
import com.kong.meirimall.product.vo.AttrResponseVo;
import com.kong.meirimall.product.vo.AttrVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kong.common.utils.PageUtils;
import com.kong.common.utils.Query;

import com.kong.meirimall.product.dao.AttrDao;
import com.kong.meirimall.product.entity.AttrEntity;
import com.kong.meirimall.product.service.AttrService;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    CategoryService categoryService;
    @Autowired
    AttrService attrService;
    @Autowired
    private AttrDao attrDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        //1、保存基本数据
        this.save(attrEntity);
        //2、保存关联关系
        AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
        if(entity.getAttrGroupId()!=null){
            if(attrEntity.getAttrType()== ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
                entity.setAttrGroupId(attrVo.getAttrGroupId()); // 属性分组 id
            }
            entity.setAttrId(attrEntity.getAttrId());     // 属性 id
        }
        relationDao.insert(entity);
    }

    @Override
    public PageUtils queryPageAttr(Map<String, Object> params, Long catalogId, String type) {
        System.out.println(params);
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        String  key = (String) params.get("key");
        System.out.println("key:"+key);
        if(!StringUtils.isEmpty(key)){
            wrapper.and((obj)->{
                obj.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        if(catalogId!=0){
            wrapper.eq("catalog_id",catalogId);
        }
        wrapper.eq("attr_type","base".equalsIgnoreCase(type)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params),wrapper);
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrResponseVo> responseVoList = records.stream().map((attrEntity) -> {
            AttrResponseVo attrRespVo = new AttrResponseVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            // 属性在其他表，不联表，分多次查
            // 查分组的名，需要先从关联表中查到 该属性的 分组id，再用 分组id 在 分组表中查
            // base 才需要设置分组信息
            if("base".equalsIgnoreCase(type)){
                AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id", attrEntity.getAttrId()));
                if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
                    AttrGroupEntity groupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    attrRespVo.setGroupName(groupEntity.getAttrGroupName());
                }
            }
            // 查分类的名，用 分类id 在分类表中查
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatalogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(responseVoList);
        return pageUtils;
    }

    @Override
    public AttrResponseVo geAttrInfo(Long attrId) {
        AttrResponseVo respVo = new AttrResponseVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, respVo);
        //设置分组信息
        if(attrEntity.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (relationEntity != null) {
                respVo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity groupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                respVo.setGroupName(groupEntity.getAttrGroupName());
            }
        }
        //设置分类信息
        Long catalogId = attrEntity.getCatalogId();
        respVo.setCatelogPath(categoryService.findCatelogPath(catalogId));
        CategoryEntity categoryEntity = categoryDao.selectById(catalogId);
        if (categoryEntity != null) {
            respVo.setCatelogName(categoryEntity.getName());
        }
        return respVo;
    }

    @Override
    public void updateAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.updateById(attrEntity);
        //修改分组关联
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        if(attrEntity.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
        }
        relationEntity.setAttrId(attrVo.getAttrId());
        UpdateWrapper<AttrAttrgroupRelationEntity> wrapper = new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId());
        //如果 attr_id匹配成功 且 attr_name 不为 null ，修改
        if(relationDao.selectCount(wrapper)>0){
            relationDao.update(relationEntity,wrapper);
        }else {
            //否则新增
            relationDao.insert(relationEntity);
        }
    }

    /**
     * 根据 分组id 查到 所有属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        //用 组id 在关联表中查，查出所有 关联对象,用该对象得到 属性id，用 属性id 在属性表中查询
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIds = relationEntities.stream().map((relationEntity) -> {
            return relationEntity.getAttrId();
        }).collect(Collectors.toList());
        if(attrIds==null || attrIds.size()==0){
            return null;
        }
        Collection<AttrEntity> attrEntities = attrService.listByIds(attrIds);
        return (List<AttrEntity>) attrEntities;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
//        relationDao.delete(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",1L)
//                .eq("attr_group_id",1L));
        //只发一个请求，批量删除
        List<AttrAttrgroupRelationEntity> relationEntities = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        relationDao.deleteBatchRelation(relationEntities);
    }

    //获取当前未关联的属性
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //1、当前分组只能关联 自己所属的分类里面的所有属性
        AttrGroupEntity groupEntity = attrGroupDao.selectById(attrgroupId);
        // 限定 该类下的
        Long catalogId = groupEntity.getCatalogId();
        //2、当前分组只能关联 该类别的分组没有引用的属性
        //   1） 查出所有组 的 id
        List<AttrGroupEntity> groupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>()
                .eq("catalog_id",catalogId));
        List<Long> groupIds = groupEntities.stream().map((obj) -> {
            return obj.getAttrGroupId();
        }).collect(Collectors.toList());
        //   2） 再用 groupId 通过关联表 查出所有关联的 属性
        QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<AttrAttrgroupRelationEntity>()
                .in("attr_group_id",groupIds);
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(queryWrapper);
        List<Long> attrIds = relationEntities.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //   3） 剔除
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catalog_id", catalogId)
                .eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(attrIds!=null&&attrIds.size()>0){
            wrapper.notIn("attr_id", attrIds);
        }
        //模糊查询条件
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {
        return baseMapper.selectSearchAttrIds(attrIds);
    }


}